package com.ycl.plus.lm.hardware.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycl.plus.lm.common.core.utils.MapstructUtils;
import com.ycl.plus.lm.common.core.utils.StringUtils;
import com.ycl.plus.lm.common.mybatis.core.page.PageQuery;
import com.ycl.plus.lm.common.mybatis.core.page.TableDataInfo;
import com.ycl.plus.lm.common.satoken.utils.LoginHelper;
import com.ycl.plus.lm.hardware.domain.HardwareEquip;
import com.ycl.plus.lm.hardware.domain.HardwareEquipSensor;
import com.ycl.plus.lm.hardware.domain.bo.HardwareEquipBo;
import com.ycl.plus.lm.hardware.domain.vo.HardwareEquipVo;
import com.ycl.plus.lm.hardware.mapper.HardwareEquipMapper;
import com.ycl.plus.lm.hardware.mapper.HardwareEquipSensorMapper;
import com.ycl.plus.lm.hardware.service.IHardwareEquipOperLogService;
import com.ycl.plus.lm.hardware.service.IHardwareEquipService;
import com.ycl.plus.lm.system.api.RemoteUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 设备Service业务层处理
 *
 * @author devil-ycl
 * @date 2024-11-07
 */
@RequiredArgsConstructor
@Service
public class HardwareEquipServiceImpl implements IHardwareEquipService {

    @SuppressWarnings("all")
    private final HardwareEquipMapper baseMapper;
    @SuppressWarnings("all")
    private final HardwareEquipSensorMapper hardwareEquipSensorMapper;
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private IHardwareEquipOperLogService hardwareEquipOperLogService;

    /**
     * 查询设备
     *
     * @param id 主键
     * @return 设备
     */
    @Override
    public HardwareEquipVo queryById(Long id) {
        HardwareEquipVo vo = baseMapper.selectVoById(id);
        if (vo != null)
            vo.setSensorIds(hardwareEquipSensorMapper.selectSensorIdsByEquipId(vo.getId()));
        return vo;
    }

    /**
     * 分页查询设备列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 设备分页列表
     */
    @Override
    public TableDataInfo<HardwareEquipVo> queryPageList(HardwareEquipBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HardwareEquip> lqw = buildQueryWrapper(bo);
        Page<HardwareEquipVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<HardwareEquipVo> records = result.getRecords();
        if (CollUtil.isEmpty(records)) {
            return TableDataInfo.build(result);
        }
        List<Long> userIds = records.stream().map(HardwareEquipVo::getUserId).toList();
        if (!userIds.isEmpty()) {
            Map<Long, String> IdName = remoteUserService.selectUsernameByIds(userIds);
            records.forEach(v -> v.setUserName(IdName.get(v.getUserId())));

            //后面要是还有要判断查询, 这句要放到后面
            result.setRecords(records);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的设备列表
     *
     * @param bo 查询条件
     * @return 设备列表
     */
    @Override
    public List<HardwareEquipVo> queryList(HardwareEquipBo bo) {
        LambdaQueryWrapper<HardwareEquip> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HardwareEquip> buildQueryWrapper(HardwareEquipBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HardwareEquip> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getActive() != null, HardwareEquip::getActive, bo.getActive());
        lqw.eq(bo.getActiveTime() != null, HardwareEquip::getActiveTime, bo.getActiveTime());
        lqw.like(StringUtils.isNotBlank(bo.getManufacturer()), HardwareEquip::getManufacturer, bo.getManufacturer());
        lqw.like(StringUtils.isNotBlank(bo.getModel()), HardwareEquip::getModel, bo.getModel());
        lqw.like(StringUtils.isNotBlank(bo.getFirmwareVersion()), HardwareEquip::getFirmwareVersion, bo.getFirmwareVersion());
        lqw.like(StringUtils.isNotBlank(bo.getSoftwareVersion()), HardwareEquip::getSoftwareVersion, bo.getSoftwareVersion());
        lqw.eq(bo.getRunStatus() != null, HardwareEquip::getRunStatus, bo.getRunStatus());
        lqw.eq(bo.getLastStartTime() != null, HardwareEquip::getLastStartTime, bo.getLastStartTime());
        return lqw;
    }

    /**
     * 新增设备
     *
     * @param bo 设备
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(HardwareEquipBo bo) {
        HardwareEquip add = MapstructUtils.convert(bo, HardwareEquip.class);
        assert add != null;
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            afterSaveBo(bo);
        }
        hardwareEquipOperLogService.insertLog(bo.getId(), LoginHelper.getUserId(), "1", "SUC", "创建设备");
        return flag;
    }

    /**
     * 修改设备
     *
     * @param bo 设备
     * @return 是否修改成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(HardwareEquipBo bo) {
        HardwareEquip update = MapstructUtils.convert(bo, HardwareEquip.class);
        assert update != null;
        validEntityBeforeSave(update);
        int i = baseMapper.updateById(update);
        boolean flag = i > 0;
        if (flag) {
            afterSaveBo(bo);
        }
        hardwareEquipOperLogService.insertLog(bo.getId(), LoginHelper.getUserId(), "1", "SUC", "修改设备");
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HardwareEquip entity) {
        //TODO 做一些数据校验,如唯一约束
        LocalDateTime now = LocalDateTime.now();
        if (entity.getId() != null) {
            entity.setUpdateTime(now);
        } else {
            entity.setCreateTime(now);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    protected void afterSaveBo(HardwareEquipBo bo) {
        List<Long> sensorIds = bo.getSensorIds();
        if (CollUtil.isNotEmpty(sensorIds)) {
            Long id = bo.getId();
            LambdaQueryWrapper<HardwareEquipSensor> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(HardwareEquipSensor::getEquipId, id);
            hardwareEquipSensorMapper.delete(wrapper);
            List<HardwareEquipSensor> list = sensorIds.stream()
                .map(v -> new HardwareEquipSensor()
                    .setEquipId(id)
                    .setSensorId(v))
                .toList();
            hardwareEquipSensorMapper.insertBatch(list);
        }
    }

    /**
     * 校验并批量删除设备信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        baseMapper.deleteByIds(ids);
        hardwareEquipOperLogService.insertLog(ids, LoginHelper.getUserId(), "1", "SUC", "删除设备");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void active(List<Long> ids) {
        LambdaUpdateWrapper<HardwareEquip> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(HardwareEquip::getActive, true)
            .in(HardwareEquip::getId, ids);
        baseMapper.update(null, wrapper);
        hardwareEquipOperLogService.insertLog(ids, LoginHelper.getUserId(), "1", "SUC", "激活设备");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long id, Integer status) {
        baseMapper.update(null,
            new LambdaUpdateWrapper<HardwareEquip>()
                .set(HardwareEquip::getRunStatus, status)
                .eq(HardwareEquip::getId, id));
        String runStatus = status == 1 ? "设备运行" : "设备停止";
        hardwareEquipOperLogService.insertLog(id, LoginHelper.getUserId(), "1", "SUC", runStatus);
    }


}
